﻿using System;
using System.Threading;

namespace Net35.Xrm.Sdk
{
	internal class ReaderWriterSlim_LockHelper : IDisposable
	{
		ReaderWriterLockSlim _lock;
		public ReaderWriterSlim_LockHelper(ReaderWriterLockSlim locker, LockType lockType)
		{
			if (locker == null)
				throw new NullReferenceException("LockReaderWriterSlim parameter locker is null. Expected non-null value.");
			_lock = locker;
			switch (lockType)
			{
				case LockType.Read:
					_lock.EnterReadLock();
					break;
				case LockType.UpgradeableRead:
					_lock.EnterUpgradeableReadLock();
					break;
				case LockType.Write:
					_lock.EnterWriteLock();
					break;
			}
		}

		public void UpgradeToWriteLock()
		{
			_lock.ExitWriteLock();
		}

		public void Dispose()
		{
			if (_lock.IsWriteLockHeld)
				_lock.ExitWriteLock();
			if (_lock.IsUpgradeableReadLockHeld)
				_lock.ExitUpgradeableReadLock();
			if (_lock.IsReadLockHeld)
				_lock.ExitReadLock();
		}
	}

	public enum LockType
	{
		Read,
		Write,
		UpgradeableRead
	}
}